package com.example.addrparserdemo.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;
import tech.spiro.addrparser.io.RegionDataInput;
import tech.spiro.addrparser.io.rdbms.RdbmsRegionDataInput;
import tech.spiro.addrparser.parser.LocationParserEngine;
import tech.spiro.addrparser.parser.ParserEngineException;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 位置解析引擎服务
 *
 * @author leiguoqing
 */
@Slf4j
@Service
public class LocationParserEngineService implements InitializingBean {

    /**
     * 位置解析引擎
     */
    private LocationParserEngine engine;

    private final ExecutorService executorService = Executors.newFixedThreadPool(1);

    /**
     * javax.sql.DataSource 数据源
     */
    @Resource
    private DataSource dataSource;

    private static final String TABLE_NAME = "t_region_data";


    public LocationParserEngine getEngine() {
        return engine;
    }


    @Override
    public void afterPropertiesSet() {
        // 关系型数据库区域数据输入
        RegionDataInput regionDataInput = new RdbmsRegionDataInput(dataSource, TABLE_NAME);

        // 创建并初始化位置解析引擎，一般配置为全局单例
        engine = new LocationParserEngine(regionDataInput);

        StopWatch sw = new StopWatch("初始化位置解析引擎");
        sw.start();

        // 初始化，加载数据，比较耗时
        // 另外开启一个线程，防止阻塞主线程
        executorService.submit(() -> {
            try {
                engine.init();
            } catch (ParserEngineException e) {
                log.error("初始化位置解析引擎异常：", e);
            }
        });

        sw.stop();
        log.info(sw.shortSummary());
    }
}
